package com.wisdytech.linkdcs.system.action;

import com.wisdytech.common.bean.StandardResult;
import com.wisdytech.common.enums.UserStatus;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.common.utils.MD5Util;
import com.wisdytech.linkdcs.system.model.SysRole;
import com.wisdytech.linkdcs.system.model.SysUser;
import com.wisdytech.linkdcs.system.service.ILoginService;
import com.wisdytech.linkdcs.system.service.ISystemResourceService;
import com.wisdytech.linkdcs.system.service.ISystemRoleService;
import com.wisdytech.linkdcs.system.service.ISystemUserService;
import com.wisdytech.linkdcs.system.vo.ResourceNodeVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/")
public class SystemAction {

    private Logger logger = LoggerFactory.getLogger(SystemAction.class);

    @Value("${cas.client-login-url}")
    private String loginUrl;


    @Resource(name = "systemRoleService")
    private ISystemRoleService systemRoleService;

    @Resource
    private ISystemResourceService sysResourceService;

    @Resource
    private ILoginService loginService;

    @Resource(name = "systemUserService")
    private ISystemUserService systemUserService;

    @RequestMapping(value={"", "/", "/index"})
    public String index() {
        return "index";
    }


    /**
     * 一般用不到
     *
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String loginForm() {
        return "redirect:" + loginUrl;
    }


    @RequestMapping("/doLogin")
    @ResponseBody
    public StandardResult doLogin(HttpServletRequest request, String username, String password) {
        UsernamePasswordToken upt = new UsernamePasswordToken(username, password);
        try {
            SysUser user = systemUserService.getUserByName(username);
            if (user != null && user.getEnabled().equals(UserStatus.DISABLE.getCode())) {
                return StandardResult.getFailResult("账号被禁用,请联系管理员");
            }
            SecurityUtils.getSubject().login(upt);
        } catch (UnknownAccountException e) {
            logger.error("登陆失败,账号错误", e);
            return StandardResult.getFailResult("登陆失败,账号错误");
        } catch (IncorrectCredentialsException e) {
            logger.error("登陆失败,密码错误错误", e);
            return StandardResult.getFailResult("登陆失败,密码错误");
        }

        //登录成功，写入session
        HttpSession session = request.getSession();
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        session.setAttribute("user", sysUser);

        //写入资源信息
        List<SysRole> roles = systemRoleService.listRoleByUserId(sysUser.getPkId());
        //TODO 目前一个用户一个角色
        List<ResourceNodeVO> resources = new ArrayList<>();
        if (roles.size() > 0) {
            resources = sysResourceService.listRoleResources(roles.get(0).getPkId());
        } else {
            resources = sysResourceService.listRoleResources("");
        }
        session.setAttribute("resources", resources);


        return StandardResult.getSuccessResult();
    }

    /**
     * 获取首页对象
     *
     * @return
     */
    @RequestMapping("/view/get.mvc")
    @ResponseBody
    public StandardResult getIndexView() {
        return StandardResult.getSuccessResult(loginService.getIndexViewVO());
    }

    /**
     * <p>Description: 验证密码正确性</p>
     *
     * @param session
     * @param password
     * @return
     */
    @RequestMapping("/validPwd/get.mvc")
    @ResponseBody
    public Map<String, Boolean> validPwd(HttpSession session, @RequestParam("password") String password) {
        Map<String, Boolean> result = new HashMap<>();

        if (StringUtils.isBlank(password)) {
            result.put("valid", false);
            return result;
        }
        SysUser currentUser = BaseUtil.getCurrentUser();
        SysUser sysUser =
                systemUserService.getUserById(currentUser.getPkId());
        String pass = MD5Util.getDigest(password);

        //密码一致
        if (sysUser.getPassword().equals(pass)) {
            result.put("valid", true);
        } else {
            result.put("valid", false);
        }

        return result;
    }

    /**
     * <p>Description: 验证新密码与原密码是否一致</p>
     *
     * @param session
     * @param password
     * @return
     */
    @RequestMapping("/validNewPwd/get.mvc")
    @ResponseBody
    public Map<String, Boolean> validNewPwd(HttpSession session, @RequestParam("new_password") String password) {
        Map<String, Boolean> result = new HashMap<>();

        if (StringUtils.isBlank(password)) {
            result.put("valid", false);
            return result;
        }
        SysUser currentUser = BaseUtil.getCurrentUser();
        SysUser sysUser =
                systemUserService.getUserById(currentUser.getPkId());
        String pass = MD5Util.getDigest(password);

        //原密码与新密码是否一致
        if (sysUser.getPassword().equals(pass)) {
            result.put("valid", false);
        } else {
            result.put("valid", true);
        }

        return result;
    }


    @RequestMapping("/updatePwd/update.mvc")
    @ResponseBody
    public StandardResult updatePwd(HttpSession session, String new_password) {

        if (StringUtils.isBlank(new_password)) {
            return StandardResult.getFailResult();
        }

        SysUser currentUser = BaseUtil.getCurrentUser();
//        String pass = MD5Util.getDigest(new_password);

        SysUser sysUser = new SysUser();
        sysUser.setPkId(currentUser.getPkId());
        sysUser.setPassword(new_password);
        return systemUserService.updateUser(sysUser);
    }

    @RequestMapping("/demo")
    public String demo() {
        return "demo";
    }

}
